import ApiFetchers from "@/apis/api_fetchers"
import { BusinessSignals } from "@/apis/api_signals"
import { ModalSlideUpStaticMethods } from "@/components/composite/ModalSlideUp/main"
import { createLogger } from "@/utils/logger"
import { signal, computed } from "@preact/signals"
import KycWarningWithCountdown from "@/components/kyc/KycWarningWithCountdown"
import KycReminderHint from "@/components/kyc/KycReminderHint"
import KycReminderInUserCenter from "@/components/kyc/KycReminderInUserCenter"
import KycReminderInDeposit from "@/components/kyc/KycReminderInDeposit"

const logger = createLogger("kycRequired")

// 源數據
export const sourceData = BusinessSignals.kycSourceData

// 定義可能需要 KYC 的動作類型
export type KycRequiredAction =
    | "deposit"
    | "withdraw"
    | "play"
    | "userCenter"
    | "home"
    | "router"
    | "afterLogin"

type Rule = {
    byPassStatus: Kyc.Status[]
    byPassCallback?: (kycStatus: Kyc.Status) => boolean
}

// KYC 狀態要求
export const kycRulesConfig = signal<Record<KycRequiredAction, Rule>>({
    // 點擊存款按鈕
    deposit: {
        byPassStatus: [
            //
            "basic_passed",
            "draft",
            "rejected",
            "pending",
            "approved",
        ],
    },
    // 開啟遊戲
    play: {
        byPassStatus: [
            //
            "unset",
            "basic_passed",
            "draft",
            "pending",
            "approved",
        ],
        byPassCallback: (status) => {
            if (status !== "approved" && BusinessSignals.hoursAfterMemberCreated.value > 48) {
                return false
            }
            return true
        },
    },
    // 進入我的帳戶
    userCenter: {
        byPassStatus: [
            //
            "basic_passed",
            "draft",
            "pending",
            "approved",
        ],
    },
    // 每當進入首頁
    home: {
        byPassStatus: [
            //
            "unset",
            "basic_passed",
            "draft",
            "pending",
            "approved",
        ],
    },
    // 進入路由
    router: {
        byPassStatus: [
            //
            "unset",
            "basic_passed",
            "draft",
            "pending",
            "approved",
        ],
    },
    // 登入後
    afterLogin: {
        byPassStatus: [
            //
            "pending",
            "approved",
        ],
    },
    // 點擊提款按鈕
    withdraw: {
        byPassStatus: [
            //
            "approved",
        ],
    },
})

// 當前 KYC 狀態 - 從 sourceData 計算得出
export const currentKycStatus = computed(() => {
    const { kyc } = sourceData.value
    if (kyc?.status) return kyc.status
    return "unset" as Kyc.Status
})

// 當前執行的動作 ID
export const currentActionId = signal<number>(0)

// 當前被阻止的動作
export const blockedAction = signal<{
    id: number
    type: KycRequiredAction
} | null>(null)

interface ExecuteStatus {
    id: number
    allowed: boolean
    currentStatus: Kyc.Status
    requiredStatus: Kyc.Status[]
    byPassCallback?: (status: ExecuteStatus) => Promise<boolean>
    action: KycRequiredAction
    sourceData: typeof sourceData.value
}

const openKycWarningWithCountdown = () => {
    ModalSlideUpStaticMethods.open("kyc-warning-with-countdown", <KycWarningWithCountdown />, {
        closeOnClickMask: false,
        position: "center",
        animation: "fade",
    })
}

const openKycReminderHint = () => {
    ModalSlideUpStaticMethods.open("root", <KycReminderHint />, {
        closeOnClickMask: false,
        position: "center",
        animation: "fade",
    })
}

const openKycReminderInUserCenter = () => {
    ModalSlideUpStaticMethods.open("root", <KycReminderInUserCenter />, {
        closeOnClickMask: false,
    })
}

const openKycReminderInDeposit = () => {
    ModalSlideUpStaticMethods.open("root", <KycReminderInDeposit />, {
        closeOnClickMask: false,
    })
}

// 預設 pendingCallback 實作
function defaultPendingCallback(status: ExecuteStatus): boolean {
    if (!BusinessSignals.isUserLogin.value) {
        return false
    }
    if (location.pathname.startsWith("/s-kyc")) {
        return false
    }
    switch (status.action) {
        case "withdraw": {
            openKycReminderHint()
            return false
        }
        case "deposit": {
            openKycReminderInDeposit()
            return false
        }
        case "play": {
            openKycWarningWithCountdown()
            return false
        }
        case "userCenter": {
            openKycReminderInUserCenter()
            return false
        }
        case "router": {
            openKycWarningWithCountdown()
            return false
        }
        case "afterLogin": {
            openKycWarningWithCountdown()
            return false
        }
    }
    return false
}

// 待執行的回調函數（可自定義）
export const pendingCallback = signal<(status: ExecuteStatus) => Promise<void>>()

// 計算當前動作是否被允許
export const isActionAllowed = computed(() => {
    const action = blockedAction.value
    const status = currentKycStatus.value
    if (!action?.type || !status) return false
    const rule = kycRulesConfig.value[action.type]
    let allowed = rule.byPassStatus.includes(status)
    if (rule.byPassCallback) {
        allowed = rule.byPassCallback(status)
    }
    return allowed
})

// signals 狀態集合
export const kycRequiredSignals = {
    sourceData,
    kycRulesConfig,
    currentKycStatus,
    blockedAction,
    pendingCallback,
    isActionAllowed,
    currentActionId,
}

interface ExecuteOptions {
    customPendingCallback?: (status: ExecuteStatus) => Promise<void>
}

/**
 * 執行 KYC 驗證
 */
export async function execute(
    action: KycRequiredAction,
    onStatus?: (status: ExecuteStatus) => Promise<void>,
    opts?: ExecuteOptions,
) {
    // 生成新的動作 ID
    currentActionId.value = Date.now()
    const actionId = currentActionId.value

    // // 更新資料
    await Promise.all([ApiFetchers.getKycV2(), ApiFetchers.refGetProfile()])

    // 檢查是否是最新的執行
    if (currentActionId.value !== actionId) {
        return
    }

    // 更新當前動作
    blockedAction.value = {
        id: actionId,
        type: action,
    }

    const status = currentKycStatus.value
    const rule = kycRulesConfig.value[action]
    const allowed = isActionAllowed.value

    // 建立狀態物件
    const executeStatus: ExecuteStatus = {
        id: actionId,
        allowed,
        currentStatus: status,
        requiredStatus: rule.byPassStatus,
        action,
        sourceData: sourceData.value,
    }

    if (allowed) {
        await onStatus?.(executeStatus)
    } else {
        // 優先使用自定義回調，其次是 signal 回調，最後是預設回調
        if (opts?.customPendingCallback) {
            await opts.customPendingCallback(executeStatus)
        } else if (pendingCallback.value) {
            await pendingCallback.value(executeStatus)
        } else {
            const result = await defaultPendingCallback(executeStatus)
            if (result) await onStatus?.(executeStatus)
        }
    }
}

/**
 * 清除特定動作的狀態
 */
export function clearAction(actionId: number) {
    if (blockedAction.value?.id === actionId) {
        blockedAction.value = null
    }
}

// 導出所有需要的內容
const kycRequiredMethods = {
    execute,
    clearAction,
    signals: kycRequiredSignals,
    kycStatus: currentKycStatus,
    openKycWarningWithCountdown,
    openKycReminderHint,
    openKycReminderInUserCenter,
}

export default kycRequiredMethods
